<?php
namespace App\Http\Admin\Middleware;

use Closure;

class CORS
{
    public function handle($request, Closure $next)
    { 
        /**
         * 用于跨域调用
         */
        if($request->isMethod('OPTIONS')){
            $response = response('',200);

        }else{
            $response = $next($request);
        }

        if($referrer = $request->server('HTTP_REFERER') ?? $request->server('HTTP_ORIGIN')){
            preg_match('/^(http[s]?:\/\/)?([^\/]+)/i', $referrer, $match);
            $response->header('Access-Control-Allow-Origin',"{$match[0]}");
            $response->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE');
            $response->header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cookies, Token,content-type');
            $response->header('Access-Control-Allow-Credentials', 'true');
            $response->header('Access-Control-Expose-Headers', 'Authorization');
            $response->header('Cache-Control', 'no-store', 'Authorization');
        }

        return $response;
    }
}